import { defineConfig, loadEnv } from 'vite';
import { wrapperEnv, createProxy } from './build/utils';
import { createVitePlugins } from './build/plugins';
import { resolve } from 'path';

function pathResolve(dir) {
	return resolve(process.cwd(), '.', dir);
}
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
	const root = process.cwd();

	const isBuild = command === 'build';
	const env = loadEnv(mode, process.cwd());
	const viteEnv = wrapperEnv(env);

	const pathResolve = (pathname) => resolve(root, '.', pathname);

	// 也可以使用process.env.xxx这种方式进行访问
	const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY } = viteEnv;

	return {
		publicPath: '/',
		plugins: createVitePlugins(viteEnv, isBuild),
		base: VITE_PUBLIC_PATH || '/',
		server: {
			host: '0.0.0.0', // 默认为'127.0.0.1'，如果将此设置为 `0.0.0.0` 或者 `true` 将监听所有地址，包括局域网和公网地址
			port: VITE_PORT, // 端口
			proxy: createProxy(VITE_PROXY), // 代理
		},
		resolve: {
			// 设置别名
			alias: [
				// @/xxxx => src/xxxx
				{
					find: /@\//,
					replacement: pathResolve('src') + '/',
				},
			],
		},
		css: {
			preprocessorOptions: {
				less: {
					modifyVars: {
						hack: `true; @import (reference) "${pathResolve('src/style/variables.less')}";`,
					},
					math: 'strict',
					javascriptEnabled: true,
				},
			},
		},

		build: {
			target: 'es2015',
			cssTarget: 'chrome80',
			rollupOptions: {
				output: {
					manualChunks(id) {
						if (id.includes('node_modules')) {
							const arr = id.toString().split('node_modules/')[2].split('/');
							switch (arr[0]) {
								case '@kangc':
								case '@naturefw':
								case '@popperjs':
								case '@vue':
								case 'axios':
								case 'vuedraggable':
								case '@vicons':
								case 'tdesign-vue-next':
								case '@tinymce/tinymce-vue':
								case '@tinymce':
								case 'tinymce-vue':
								case 'tinymce':
									return '_' + arr[0];
								default:
									return '__vendor';
							}
						}
					},
					chunkFileNames: 'static/js1/[name]-[hash].js',
					entryFileNames: 'static/js2/[name]-[hash].js',
					assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
				},
			},
		},
	};
});
